package br.com.abella.snippets.xpath;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * 
 * Used class to provide XPath consults (instead of use others parse's mechanisms - jdom, sax, and so on) 
 * 
 * @author Daniel Abella
 *
 */
public class XPathConsultsJava6 {

	private String xmlFile;

	private Document xmlDocument;

	private XPath xPath;

	public XPathConsultsJava6() {

	}
	
	/**
	 * Create all necessaries parsers to provide XPath consults.
	 * 
	 * @param xmlFile 
	 * @throws FileNotFoundException 
	 */
	public XPathConsultsJava6(String xmlFile) throws FileNotFoundException {
		
		if(xmlFile == null)
			throw new FileNotFoundException("Null cant be indicated. Indicate the correct path of file");
		
		this.xmlFile = xmlFile;
		initParser();
	}

	/**
	 * Initializate parser
	 *
	 */
	private void initParser() {
		
		try {
			xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
			xPath = XPathFactory.newInstance().newXPath();
		} catch (IOException e) {			
			Logger.getLogger("global").log(Level.SEVERE, "VEPersonal Report: IOException has been throwed. Please contact the administrator", e);
		} catch (SAXException e) {
			Logger.getLogger("global").log(Level.SEVERE, "VEPersonal Report: SAXException has been throwed. Please contact the administrator", e);
		} catch (ParserConfigurationException e) {
			Logger.getLogger("global").log(Level.SEVERE, "VEPersonal Report: ParseConfigurationException has been throwed", e);
		}
	}

	/**
	 * Process XPath consult.
	 * 
	 * @param expression
	 * @param returnType
	 * @return
	 */
	public Object read(String expression, QName returnType) {
		
		try {
			XPathExpression xPathExpression = xPath.compile(expression);
			return xPathExpression.evaluate(xmlDocument, returnType);
		} catch (XPathExpressionException ex) {
			Logger.getLogger("global").log(Level.SEVERE, "VEPersonal Report: XPathExpressionException has been throwed", ex);
			return null;
		}
	}
	
	@Test
	public void makeXPathConsult() throws Exception {
		
		XPathConsultsJava6 consult = new XPathConsultsJava6("projects.xml");
		
		consult.initParser();
		
		//Object result = consult.read("//", javax.xml.namespace.QName.Da);
		
		
	}
	
	
}
